package com.lun.easy;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import com.lun.util.BinaryTree.TreeNode;

public class BinaryTreePreorderTraversal {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        preorderTraversal(root, result);
        return result;
    }
    
    private void preorderTraversal(TreeNode root, List<Integer> result){
        if(root == null) return;
        result.add(root.val);
        preorderTraversal(root.left, result);
        preorderTraversal(root.right, result);
    }
    
    
    public List<Integer> preorderTraversal2(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        LinkedList<TreeNode> stack = new LinkedList<>();
        if(root != null) stack.push(root);
        
        while(!stack.isEmpty()) {
        	TreeNode node = stack.pop();
        	
        	result.add(node.val);
        	if(node.right != null)
        		stack.push(node.right);
        	if(node.left != null)
        		stack.push(node.left);
        }
        
        return result;
    }

}
